from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import (
    CreateView,
    UpdateView,
    DetailView,
    DeleteView,
    ListView,
)

from .models import Network, Station
from .forms import (
    NetworkForm,
    StationForm,
)


def index(request):
    return render(request, template_name='index.html')


class NetworkListView(ListView):
    model = Network
    template_name = "basic/network_list.html"
    context_object_name = "network_list"


class NetworkCreateView(CreateView):
    model = Network
    form_class = NetworkForm
    template_name = "basic/network_add.html"
    context_object_name = "network"
    success_url = reverse_lazy('basic:network_list')


class NetworkUpdateView(UpdateView):
    model = Network
    form_class = NetworkForm
    template_name = 'basic/network_edit.html'
    context_object_name = "network"
    success_url = reverse_lazy('basic:network_list')


class NetworkDeleteView(DeleteView):
    model = Network
    template_name = 'basic/network_delete.html'
    context_object_name = "network"
    success_url = reverse_lazy('basic:network_list')


class StationCreateView(CreateView):
    model = Station
    form_class = StationForm
    template_name = 'basic/station_add.html'
    context_object_name = "station"
    success_url = reverse_lazy('basic:station_list')


class StationUpdateView(UpdateView):
    model = Station
    form_class = StationForm
    template_name = 'basic/station_edit.html'
    context_object_name = "station"
    success_url = reverse_lazy('basic:station_list')


class StationDeleteView(DeleteView):
    model = Station
    template_name = 'basic/station_delete.html'
    context_object_name = "station"
    success_url = reverse_lazy('basic:station_list')


class StationListView(ListView):
    model = Station
    template_name = 'basic/station_list.html'
    context_object_name = 'station_list'
    paginate_by = 10

    def get_queryset(self):
        print(self.request.GET)
        print(self.request.GET.dict())
        print(self.request.GET is not None)
        print(self.request.GET.get('net__id__exact'))
        params = self.request.GET.dict()

        if self.request.GET is not None:
            params = self.request.GET.dict()
            if 'page' in params:
                params.pop('page')
            qs = Station.objects.filter(**params)
        else:
            qs = Station.objects.all()

        return qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        network_list = Network.objects.all()
        context['status_type'] = Station.STATUS_TYPE
        context['network_list'] = network_list
        return context


class StationDetailView(DetailView):
    model = Station
    template_name = 'basic/station_detail.html'
    context_object_name = 'station'